<?
/**************************************************************************************************
网站管理系统
Author			warmy
Version			1.0
Create Date		2006-10-26
**************************************************************************************************
功能树
**************************************************************************************************/
class Warmy_tree extends ANotify
{
	//construct
	protected 	$db;					//数据库连接
	public 		$fun;					//功能编号
	private 	$tablename;
	function Warmy_tree(& $db, $right,$checkright=false,$tablename=FUNCTIONTABLE)
	{
		$this->db		= $db;
		$this->fun		 = array();
		$this->tablename = $tablename;
		$str_right		= "";
		//组合功能编号字符串
		if(is_array($right))
		{
			$str_right = implode(",",array_keys($right));
		}
		//获取功能详细信息的SQL语句
		$sql = "select id,root,name,href,idx,deep,case type when 'S' then '系统' when 'P' then '发布' else '用户' end as type,micro from `{$this->tablename}` ";
		if($str_right != "")
			$sql .= "where id in($str_right) ";
		else if($checkright)
		{
			$sql .= "where 1=3 ";
		}
		$sql .= "order by idx";
		
		if(($query = $db->query($sql))==true)
		{
			while(($row = mysql_fetch_array($query,MYSQL_ASSOC))==true)
				array_push($this->fun,$row);
		}
		
	}
	/**************************************************************************************************
	返回功能树字符串及功能参数
	**************************************************************************************************/
	function Get_Tree()
	{
		$len					= count($this->fun);
		$out_str				= '';
		$path					= array();
		$fun_cache				= array();
		$deep					= 1;
		for($i=0;$i<$len;$i++)
		{
			if($this->fun[$i]["deep"]>1 && $out_str=='')
				continue;
			//把功能名称压入堆栈


			//if(!is_array($path))
			//	$path			= array();
			array_push($path,$this->fun[$i]["name"]);
			if($this->fun[$i]["deep"] == 0)
			{
				if($i>0 && $this->fun[$i-1]["deep"] > $this->fun[$i]["deep"])
					$out_str = "{$out_str}</table></td></tr>";
				$out_str = "{$out_str}<tr class='xx'><td class=\"menuNomorl\">{$this->fun[$i]["name"]}</td></tr>";
				if(isset($this->fun[$i+1]) && $this->fun[$i+1]["deep"]>$this->fun[$i]["deep"] )
				{
					$out_str = "{$out_str}<tr class=\"menuBoxH\"><td><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
				}
			}
			else 
			{
				$href			= ATHENA_SCRIPT_INDEX . "?Model={$this->fun[$i]["id"]}";
				$space			= str_repeat("　",$this->fun[$i]["deep"]);
				$out_str = "{$out_str}<tr><td>{$space}<a href=\"$href\">{$this->fun[$i]["name"]}</a></td></tr>";
				if(!isset($this->fun[$i+1]))
				{
					$out_str = "{$out_str}</table></td></tr>";
				}
			}
			//组合当前功能点的路径
			$fun_cache[$this->fun[$i]["id"]]['PATH'] = implode(" &gt;&gt; ",$path);
			//当前节点名称
			$fun_cache[$this->fun[$i]["id"]]['NAME'] = $this->fun[$i]["name"];
			//当前节点的模板路径


			$fun_cache[$this->fun[$i]["id"]]['HREF'] = $this->fun[$i]["href"];
			//当下一个节点的深度小于当前节点的深度，则弹出路径数组中无效的数据


			if(isset($this->fun[$i+1]))
			{
				if($this->fun[$i+1]["deep"]<$this->fun[$i]["deep"])
				{
					//深度差别
					$step = $this->fun[$i]["deep"] - $this->fun[$i+1]["deep"];
					while ($step-->0) {
						array_pop($path);
					}
					if(count($step)>0)
						array_pop($path);
				}
				elseif($this->fun[$i+1]["deep"]==$this->fun[$i]["deep"])
				{
					
					array_pop($path);
				}
			}
		}
		if($len>0&&$this->fun[$len-1]["deep"]>0)
			$out_str = "{$out_str}";
		$fun_cache['TREE'] = $out_str;
		return $fun_cache;
	}
	/**
	 * 输入目录树
	 *
	 */
	function Print_Tree()
	{
		//获取当前功能编号
		$current_fun			= 0;
		$current_fun_tmp		= 0;
		$current_deep			= 0;
		if(isset($_GET['Model']) && ereg("^[0-9]+$",$_GET['Model']))
			$current_fun_tmp	= $_GET['Model'];
		$out_str				= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
		//$deep					= 0;
		$len					= count($this->fun);
		$root					= -1;
		for($i=0;$i<$len;$i++)
		{
			if($i>0)
			{
				if($this->fun[$i]["deep"] == 0 && $this->fun[$i-1]["deep"] > $this->fun[$i]["deep"])
					$out_str	= "$out_str</table></td></tr>";
			}
			
			if($this->fun[$i]["deep"] == 0)
			{
				$out_str		= "$out_str<tr onclick=\"OpenChildren({$this->fun[$i]["id"]})\"><td height=\"20\" background=\"images/back_r5_c2.jpg\" style=\"text-align:left;size:9pt;\">·{$this->fun[$i]['name']}</td>	</tr>";
				if(isset($this->fun[$i+1]) && $this->fun[$i+1]["deep"]>$this->fun[$i]["deep"])
					$out_str	= "$out_str<tr><td width=\"100%\"><table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" id=\"menu{$this->fun[$i]["id"]}\" style=\"display:none\">";
				if($current_fun_tmp > 0)
					$root			= $i;
			}
			else
			{
				if($current_fun_tmp > 0 && $current_fun_tmp == $this->fun[$i]["id"])
				{
					$current_fun	= $current_fun_tmp;
					$current_fun_tmp=-1;
					$current_deep	= $this->fun[$i]["deep"];
				}
				$out_str			= "$out_str<tr><td height=\"1\"></td></tr>";
				$space			= str_repeat("&nbsp;&nbsp;",$this->fun[$i]["deep"]);
				if($this->fun[$i]["href"] == "")
					$href			= "";
				else
					$href			= "href=\"".ATHENA_SCRIPT_INDEX."?Model={$this->fun[$i]["id"]}\"";
				$out_str		= "$out_str<tr><td height=\"20\" background=\"images/back_r8_c2.jpg\" style=\"text-align:left;\">$space ·<a $href>{$this->fun[$i]['name']}</a></td></tr>";
			}
		}
		if($len > 0 && $this->fun[$len-1]["deep"]>0)
				$out_str	= "$out_str</table></td></tr>";
	
		if($root > -1)
			$out_str		= str_replace("id=\"menu{$this->fun[$root]["id"]}\" style=\"display:none\"","id=\"menu{$this->fun[$root]["id"]}\"",$out_str);
		//组合路径
		$deep				= -1;
		$path				= "";
		if($root > -1)
		{	
			$root = $current_fun;
			for($i=$len-1;$i>=0;$i--)
			{
				if($this->fun[$i]["id"] == $root)
				{
					if($path == "")
						$path = $this->fun[$i]["name"];
					else 
						$path = $this->fun[$i]["name"] . " &gt;&gt; " . $path;
					$root = $this->fun[$i]["root"];
					if($this->fun[$i]["deep"] == 0)
						break;
				}
			}
			$path =	" &gt;&gt; $path";
		}
		$out_str			= "$out_str<tr><td height=\"20\" background=\"images/back_r5_c2.jpg\" style=\"text-align:left;size:9pt;\">·<a href=\"logout.php\" style=\"color:#000000\">登出</a></td></tr>";
		$out_str			= "$out_str</table></td><td valign=\"top\" height=\"400\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" height=\"100%\"><tr><td width=\"21\"><img src=\"images/back_r3_c4.jpg\" width=\"21\" height=\"31\"></td><td background=\"images/back_r3_c5.jpg\">&nbsp;</td></tr><tr><td background=\"images/back_r6_c4.jpg\"></td><td height=\"20\" style=\"color:#034488;background-color:#EBEFF2\">&nbsp;&nbsp;○ Home $path";
		$out_str			= "$out_str</td></tr><tr><td background=\"images/back_r6_c4.jpg\"><img src=\"images/back_r6_c4.jpg\"></td><td valign=\"top\" width=\"100%\" height=\"100%\"><br>";
		print($out_str);
	}
	/**************************************************************************************************
	返回指定功能点的HREF
	**************************************************************************************************/
	function get_HREF($Model)
	{
		for($i=0;$i<count($this->fun);$i++)
		{
			if($this->fun[$i]["id"] == $Model)
				return $this->fun[$i]["href"];
		}
		return "";
	}
	function View($href="",$edit=true)
	{
		$out_str	= "";
		for($i=0;$i<count($this->fun);$i++)
		{
			$out_str		= "$out_str<tr>";
			if($edit)
			{
				$space			= str_repeat("&nbsp;&nbsp;",$this->fun[$i]["deep"]);
				$out_str	= "$out_str<td><input type=\"checkbox\" name=\"id[]\" value=\"{$this->fun[$i]["id"]}\"></td>";
				$out_str		= "$out_str<td width=\"40%\">$space<a href=\"$href{$this->fun[$i]["id"]}\">{$this->fun[$i]["name"]}</a></td>";
			}
			else
			{
				$space			= str_repeat("&nbsp;&nbsp;",$this->fun[$i]["deep"]+1);
				if(isset($this->fun[$i+1]) && $this->fun[$i+1]["deep"]>$this->fun[$i]["deep"])
					$out_str		= "$out_str<td width=\"40%\">$space<a href=\"$href{$this->fun[$i]["id"]}\">{$this->fun[$i]["name"]}</a></td>";
				else
					$out_str		= "$out_str<td width=\"40%\">$space{$this->fun[$i]["name"]}</td>";
			}
			$out_str		= "$out_str<td width=\"10%\">{$this->fun[$i]["type"]}</td>";
			$out_str		= "$out_str<td width=\"50%\">{$this->fun[$i]["href"]}</td></tr>";
		}
		return $out_str;
	}
	function View_Option($id = 0)
	{
		$out_str	= "";
		for($i=0;$i<count($this->fun);$i++)
		{
			$out_str		= "$out_str<option value=\"{$this->fun[$i]["id"]}\"";
			$space			= str_repeat("&nbsp;&nbsp;",$this->fun[$i]["deep"]);
			if($id == $this->fun[$i]["id"])
				$out_str	= "$out_str selected";
			$out_str	= "$out_str>$space{$this->fun[$i]["name"]}</option>";
		}
		return $out_str;
	}
	function Update($id,$root,$name,$href,$type,$model,$url,$micro)
	{
		if($id == $root)
			$this->halt("不能选择自己为自己的父目录");
		$deep				= 0;
		$len				= count($this->fun);
		if($root != 0 )
		{
			for($i=0;$i<$len;$i++)
			{
				if($this->fun[$i]["id"] == $root)
				{
					$deep	= $this->fun[$i]["deep"];
					break;
				}
			}
			if($i>=$len)
				$this->halt("选择的上级目录已经被删除！");
			$deep++;
		}
		if($micro == -1)
			$sql = "update `{$this->tablename}` set `root`='$root',`name`='$name',`href`='$href',`deep`='$deep',`type`='$type',`model`='$model',`url`='$url' where id='$id'";
		else 
			$sql = "update `{$this->tablename}` set `root`='$root',`name`='$name',`href`='$href',`deep`='$deep',`type`='$type',`model`='$model',`url`='$url',`micro`='$micro' where id='$id'";
		$this->db->query($sql);
		$this->Resort();
		$this->Create_Publish_Directory($url);
		$this->Create_Program($href,$model);
		return true;
	}
	
	function Create_Publish_Directory($url)
	{
		//创建发布目录
		$arr	= pathinfo($url);
		if(!isset($arr["dirname"]))
			return;
		$path	= trim($arr["dirname"],"/");
		$wfile	= new WFile();
		try 
		{
			$wfile->CreateDir($path);
		}
		catch (Exception $e)
		{
			$this->halt($e->getMessage());
		}
		
	}
	/**
	 * 创建相关程序
	 *
	 * @param unknown_type $href		管理模板存放位置
	 * @param unknown_type $modelid		模块代码
	 */
	function Create_Program($href,$modelid)
	{
		$path	= MANAGE_VIRTUAL . "template/$href";
		$arr	= pathinfo($path);
		$path	= trim($arr["dirname"],"/");
		$wfile	= new WFile();
		//创建对应的管理目录
		try 
		{
			$wfile->CreateDir($path);
		}
		catch (Exception $e)
		{
			$this->halt($e->getMessage());
		}
		//创建程序
		$sql	= "select program,struct from ".WMODELTABLE." where modelid='$modelid'";
		$row	= $this->db->query_row($sql,MYSQL_NUM);
		if(count($row))
		{
			$filename	= DOCUMENTROOT . MANAGE_VIRTUAL . "template/$href";
			if(!file_exists($filename))
			{
				$wfile->write_to_file($filename,html_entity_decode($row[0][0],ENT_QUOTES));
			}
			$filename	= DOCUMENTROOT . '/'.$path . "/" . STRUCT_NAME;
			if(!file_exists($filename))
			{
				$wfile->write_to_file($filename,html_entity_decode($row[0][1],ENT_QUOTES));
			}
		}
	}
	function AddNew($root,$name,$href,$type,$model,$url,$micro)
	{
		$deep				= 0;
		$len				= count($this->fun);
		if($root != 0 )
		{
			for($i=0;$i<$len;$i++)
			{
				if($this->fun[$i]["id"] == $root)
				{
					$deep	= $this->fun[$i]["deep"];
					break;
				}
			}
			if($i>$len)
				$this->halt("选择的上级目录已经被删除！");
			$deep++;
		}
		$len++;
		if($root>32 && $root <100 && isset($_POST['product']) && $_POST['product'] == "1")
		{
			//获取可使用编号
			$sql = "select id from `{$this->tablename}` where id>32 && id<100";
			$row = $this->db->query_row($sql,MYSQL_NUM);
			$id	 = 0;
			$use = array();
			while (list(,$value) = each($row)) 
				array_push($use,$value[0]);
			for($i=33;$i<100;$i++)
			{
				if(array_search($i,$use) === false)
				{
					$id = $i;
					break;
				}
			}
			if($id == 0 )
				$this->halt('程序溢出！');
			if($micro == -1)
				$sql = "insert into `{$this->tablename}` values('$id','$root','$name','$href','$len','$deep','$type','$url','$model',0)";
			else 
				$sql = "insert into `{$this->tablename}` values('$id','$root','$name','$href','$len','$deep','$type','$url','$model','$micro')";
				
		}
		else
		{
			if($micro == -1)
				$sql = "insert into `{$this->tablename}`(`root`,`name`,`href`,`deep`,`idx`,`type`,`url`,`model`) values('$root','$name','$href','$deep','$len','$type','$url','$model')";
			else 
				$sql = "insert into `{$this->tablename}`(`root`,`name`,`href`,`deep`,`idx`,`type`,`url`,`model`,`micro`) values('$root','$name','$href','$deep','$len','$type','$url','$model','$micro')";
		}
		$this->db->query($sql);
		$this->Resort();
		//创建目录
		$this->Create_Publish_Directory($url);
		$this->Create_Program($href,$model);
		return true;
	}
	function SaveSort($idx)
	{
		$arr = split(",",$idx);
		for($i=0;$i<count($arr);$i++)
			$this->db->query("update `{$this->tablename}` set idx=" . ($i+1) . " where Id=" . $arr[$i]);
		$this->Resort();
	}
	function DeleteFun($id)
	{
		$str		= "";
		for($i=0;$i<count($id);$i++)
		{
			$str	= "$str,{$id[$i]}";
			for($j=0;$j<count($this->fun);$j++)
			{
				if($this->fun[$j]["id"] == $id[$i])
					array_splice($this->fun,$j,1);
				if(isset($this->fun[$j]))
				{
					for($k=$j;$k<count($this->fun);$k++)
					{
						if($this->fun[$k]["root"] == $id[$i])
						{
							if(array_search($this->fun[$k]["id"],$id) == false)
								array_push($id,$this->fun[$k]["id"]);	
							array_splice($this->fun,$k,1);
							$k--;
						}
					}
				}
			}
		}
		if(ereg("^[0-9,]+$",$str))
		{
			$str	= substr($str,1);
			$sql = "delete from `{$this->tablename}` where id in($str) and type!='S'";
			$this->db->query($sql);
		}
		else
			$this->halt("没有选择需要删除的功能点！");
	}
	function PrintTreeEx(&$uright,$root=0,$deep=1)
	{//print_r($uright);

		for($i=0;$i<count($this->fun);$i++)
		{
			if($this->fun[$i]['root'] == $root)
			{
				$Id		= $this->fun[$i]["id"];
				$Name	= $this->fun[$i]['name'];
				$micro	= $this->fun[$i]['micro'];
				$checked = "";
				if(array_key_exists($Id,$uright) == true)	
					$checked = " checked";
				//for($j=0;$j<count($uright);$j++)
				//	if($Id==$uright[$j])
						
				if ($this->TreeChildren($Id) == 0 )
				{
					print("<li><input type=\"checkbox\" name=\"Id[]\" $checked value=\"$Id\" root=\"$root\" >");
					print($Name);
					if(defined('MICRO_RIGHT_SET'))
					{
						print(" &nbsp;&nbsp;<a href=\"#\" onclick=\"micro_right(this,$Id,$micro)\">设置</a><input type=\"hidden\" name=\"fun_$Id\" value=\"");
						if(isset($uright[$Id]))
							print($uright[$Id]);
						else 
							print("0");
						print("\">");
					}
					print("</li>");
					/*
					print("<tr><td  nowrap style=\"text-align:left\">");
					print("<input type=\"checkbox\" name=\"Id[]\" $checked value=\"$Id\" root=\"$root\" >");
					print($Name);
					print(" &nbsp;&nbsp;<a href=\"#\" onclick=\"micro_right(this,$Id,$micro)\">设置</a><input type=\"hidden\" name=\"fun_$Id\" value=\"");
					if(isset($uright[$Id]))
						print($uright[$Id]);
					else 
						print("0");
					print("\"></td><tr>");
					*/
				}
				else
				{
					print("<li>");
					print("<img src=\"css/images/plus.gif\"  >");
					print("<input type=\"checkbox\" name=\"Id[]\" $checked value=\"$Id\" root=\"$root\" >");
					print($Name);
//					print("</li><ul style='display:none;'>");
//					$this->PrintTreeEx($uright,$Id,$deep+1);
//					print("</ul>");
					print("<ul style='display:none;'>");
					$this->PrintTreeEx($uright,$Id,$deep+1);
					print("</ul></li>");
					/*
					print("<tr style=\"cursor:hand;\"><td colspan=\"2\" width=\"100%\" nowrap><p align=\"left\"><img src=\"images/plus.gif\" onclick=\"TreeDisplay('root$Id')\" >");
					print("<input type=\"checkbox\" name=\"Id[]\" $checked value=\"$Id\" root=\"$root\" >");
					print($Name);
					print("</p></td><tr>");
					print("<tr Id=\"root$Id\" style=\"display:none;\"><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td width=\"100%\">");
					print("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\" align=\"center\" class=\"TREE\">");
					$this->PrintTreeEx($uright,$Id,$deep+1);
					print("</table>");
					print("</td></tr>");
					*/
				}	
			}
		}
		
		
		
	}
	//计算当前节点含有子节点数量
	function TreeChildren($Id)
	{
		$children = 0;
		for($i=0;$i<count($this->fun);$i++)
		{
			if($this->fun[$i]['root'] == $Id)
				$children++;
		}
		return $children;
	}

	function Resort()
	{
		$sql	= "select name,id,deep,root from `{$this->tablename}` order by root,idx";
		$row	= $this->db->query_row($sql,MYSQL_ASSOC);
		$sort	= array();
		$p		= 0;
		while(count($row) > 0)
		{
			$tmp	= array_shift($row);
			array_push($sort,$tmp);
			while($p<count($sort))
			{
				$size	= count($row);
				$offset = -1;
				$len	= 0;
				
				for($i=0;$i<$size;$i++)
				{
					if($sort[$p]["id"] == $row[$i]["root"])
					{
						if($len == 0)
							$offset = $i;
						$len++;
					}
				}
				$p++;
				if($offset != -1)
				{
					$a		= array_slice($sort,0,$p);
					$tmp	= array_splice($row,$offset,$len);
					if(count($sort)>$p)
					{
						$sort	= array_slice($sort,$p,count($sort)-$p);
						$sort	= array_merge($a,$tmp,$sort);
					}
					else 
						$sort	= array_merge($a,$tmp);
					
				}
				
			}
		}
		$len	= count($sort);
		for($i=0;$i<$len;$i++)
		{
			$idx	= $i + 1;
			$sql = "update `{$this->tablename}` set idx=$idx where id='{$sort[$i]["id"]}';";
			$this->db->query($sql);
		}		
	}
	function getSon($parent)
	{
		$this->fun = $this->db->query_row("select id,name,root from `{$this->tablename}` where root='$parent' order by idx",MYSQL_ASSOC);
		//print_r($this->fun);
	}
}


?>